package com.itheima.sfbx.insurance.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.constant.basic.SuperConstant;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.enums.SafeguardEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.pojo.InsuranceCoefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import com.itheima.sfbx.insurance.service.IInsuranceCoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/**
 * @Description：系数项服务实现类
 */
@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {

    @Autowired
    private ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    private IInsuranceCoefficentService insuranceCoefficentService;


    @Override
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        //
        Page<Coefficent> page = this.lambdaQuery()
                .eq(StringUtils.isNotBlank(coefficentVO.getCoefficentKey()), Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .like(StringUtils.isNotBlank(coefficentVO.getCoefficentKeyName()), Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
                .eq(StringUtils.isNotBlank(coefficentVO.getDataState()), Coefficent::getDataState, coefficentVO.getDataState())
                .page(new Page<>(pageNum, pageSize));

        return BeanConv.toPage(page, CoefficentVO.class);
    }

    @Override
    public CoefficentVO findById(String coefficentId) {
        //TODO
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CoefficentVO save(CoefficentVO coefficentVO) {
        //检查数据库中是否已存在具有相同coefficientKey的记录
        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .eq(Coefficent::getCoefficentType, SuperConstant.DATA_STATE_0)
                .count();
        if(count > 0){
            // 如果存在，记录错误日志并抛出异常，防止重复添加
            log.error("新增系数项失败, 因为key已经存在:{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        // 检查数据库中是否已存在具有相同coefficientKeyName的记录
        count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKeyName, coefficentVO.getCoefficentKeyName())
                .eq(Coefficent::getDataState, SuperConstant.DATA_STATE_0)
                .count();
        if (count > 0) {
            // 如果存在，记录错误日志并抛出异常，防止重复添加
            log.error("新增保障项失败, 因为keyName已经存在:{}", coefficentVO.getCoefficentKeyName());
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        // 将传入的VO对象转换为实体类对象，准备保存
        Coefficent bean = BeanConv.toBean(coefficentVO, Coefficent.class);
        // 将保存后的实体类对象转换为VO对象并返回
        return BeanConv.toBean(bean, CoefficentVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(CoefficentVO coefficentVO) {
        // 根据ID获取系数实体
        Coefficent bean = this.getById(coefficentVO.getId());
        // 检查实体是否存在，如果不存在，则记录错误日志并抛出异常
        if(bean == null){
            log.error("数据不存在:{}", coefficentVO.getId());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        // 检查系数键是否已存在于其他系数实体中，以确保唯一性
        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .ne(Coefficent::getId, coefficentVO.getId())
                .count();
        // 如果存在，记录错误日志并抛出异常
        if(count > 0){
            log.error("修改保障项失败, 因为key已经存在:{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(SafeguardEnum.UPDATE_FAIL);
        }
        // 查询保障键是否在分类保障项中使用
        Integer count1 = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        // 查询保障键是否在计划保障项中使用
        Integer count2 = insuranceCoefficentService.lambdaQuery()
                .eq(InsuranceCoefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        // 如果保障键在分类保障项或计划保障项中使用，记录错误日志并抛出异常
        if(count1 > 0 || count2 > 0){
            log.error("修改保障项失败, 有关联关系:{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        // 更新保障项实体
        return this.updateById(BeanConv.toBean(coefficentVO, Coefficent.class));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(String[] checkedIds) {
        //
        boolean result = false;
        for (String id : checkedIds) {
            // 根据ID获取保障项实体
            Coefficent bean = this.getById(id);
            // 检查保障项实体是否存在
            if(bean == null){
                // 如果不存在，记录错误日志并抛出异常
                log.error("数据不存在:{}", id);
                throw new ProjectException(CoefficentEnum.DEL_FAIL);
            }
            // 查询保障键是否在分类保障项中使用
            Integer count1 = categoryCoefficentService.lambdaQuery()
                    .eq(CategoryCoefficent::getCoefficentKey, bean.getCoefficentKey())
                    .count();
            // 查询保障键是否在计划保障项中使用
            Integer count2 = insuranceCoefficentService.lambdaQuery()
                    .eq(InsuranceCoefficent::getCoefficentKey, bean.getCoefficentKey())
                    .count();
            // 如果保障键在分类保障项或计划保障项中使用，记录错误日志并抛出异常
            if(count1 > 0 || count2 > 0){
                log.error("删除保障项失败, 有关联关系:{}", bean.getCoefficentKey());
                throw new ProjectException(SafeguardEnum.DEL_FAIL);
            }
            result = this.removeById(id);
        }
        return result;
    }

    @Override
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        //TODO
        return null;
    }

    @Override
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        //TODO
        return null;
    }
}
